#!/bin/bash
function log
{
	if [ $? -eq 0 ]
	then
		echo "$1 SUCCESS!"
	else
		echo "$1 FAILED!"
		if [ "xtrue" = "x$2" ]
		then
			exit 1;
		fi
	fi
}

function usage
{
	echo "adsf"
}

ROOT=`pwd`
function options
{
	# Execute getopt
	ARGS=`getopt -a -o "p:" -l "prefix:" -n "$0" -- "$@"`

	#Bad arguments
	if [ $? -ne 0 ];
	then
		usage
		exit 1
	fi
	# A little magic
	eval set -- "$ARGS"

	# Now go through all the options
	while true;
	do
		case "$1" in
		-p|--prefix)
			TMPPATH="$2"
			if [ "${TMPPATH:0:1}" == "/" ]
			then
				ROOT="$TMPPATH"
			else
				ROOT="$ROOT/$TMPPATH"
			fi
			shift 2;;
		--)
			shift
			break;;
		*)
			echo "error" >2;
			break;;
		esac
	done

}
options "$@"

echo "Root     :$ROOT"

DOWNLOAD="$ROOT/download"
echo "Download :$DOWNLOAD"

BUILD="$ROOT/build"
echo "Build    :$BUILD"

INSTALL="$ROOT/external"
echo "Install  :$INSTALL"

function download
{
	LIB_NAME="$1"
	URL="$2"
	PACKAGE_NAME=`basename $URL`
	DOWNLOAD_PATH="$DOWNLOAD/$LIB_NAME"
	if [ -d "$DOWNLOAD_PATH" ]
	then
		rm -rf "$DOWNLOAD_PATH/*"
	else
		mkdir -p "$DOWNLOAD_PATH"
	fi

	if [ ! -r "$DOWNLOAD_PATH" ]
	then
		false
		log "Download Directory can't be read : $DOWNLOAD_PATH" true
	fi

	if [ ! -w "$DOWNLOAD_PATH" ]
	then
		false
		log "Download Directory can't be writed : $DOWNLOAD_PATH" true
	fi

	wget -nv -P "$DOWNLOAD_PATH" "$URL"
	log "Download $LIB_NAME"
}

function uncompress
{
	echo 
}


function compile_install
{
	echo 
}

function doci
{
	LIB_NAME="$1"
	URL="$2"
	download "$LIB_NAME" "$URL"
}

xmllint -auto -xpath "/info" >/dev/null 2>&1
if [ $? -ne 0 ]
then
	doci "libxml2" "http://127.0.0.1/libxml2-2.9.0-rc1.tar.gz" 
fi

#WGET="wget -c -nv -P  \"$DOWNLOAD\""
#echo "Downloading:boost_1_51_0.tar.gz"
#$WGET "http://sourceforge.net/projects/boost/files/boost/1.51.0/boost_1_51_0.tar.gz" & 
#WGET_BOOST_PID=$!
#
#echo "Downloading:gmime-2.6.10.tar.xz"
#$WGET "ftp://ftp.gnome.org/pub/GNOME/sources/gmime/2.6/gmime-2.6.10.tar.xz"&
#WGET_GMIME_PID=$!
#wait $WGET_BOOST_PID $WGET_GMIME_PID
echo "Finish"
